//
//  LTY_FilmAndSongsViewController.m
//  MooMusic
//
//  Created by 守护神 on 15/10/21.
//  Copyright © 2015年 wjy. All rights reserved.
//

#import "LTY_FilmAndSongsViewController.h"
// 导入自定义cell的头文件
#import "LTY_FilmAndSongsTableViewCell.h"
// 导入下拉放大高斯模糊的三方头文件
#import "LO_GaussianBlur.h"
#import "LO_HeaderView.h"
// 导入shareSDK头文件
#import <ShareSDK/ShareSDK.h>
// 腾讯头文件
#import <TencentOpenAPI/QQApiInterface.h>
#import <TencentOpenAPI/TencentOAuth.h>
// 导入NetWork头文件
#import "NetWork.h"
// 导入每日十首的model的头文件
#import "LTY_TenSongsModel.h"

/* 导入数据库头文件*/
#import "FilmAndSongs.h"

#define shareAppKey @"b7fe5c3bf8f4"


#define WIDTHBOUNDS self.view.frame.size.width
#define HEIGHTBOUNDS 180


@interface LTY_FilmAndSongsViewController ()<UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate>

@property (nonatomic, strong)UITableView *detailTableview;
@property (nonatomic, strong)UIView *headerView;
@property (nonatomic, strong) LO_HeaderView *headerImage;
@property (nonatomic, strong)UIButton *shareButton;
// 设置数据源
@property (nonatomic, strong)NSMutableArray *dataArray;
// 设置存放音乐播放url的数据源
@property (nonatomic, strong)NSMutableArray *urlListArray;
// 设置一个数组 来存放临时的
@property (nonatomic, strong)NSMutableArray *songsArr;



/* 设置一个临时数组 来接收数据库中的值 */
@property (nonatomic, strong) NSMutableArray *sqliteArr;




@property (nonatomic, strong) TabBarController *tabBarSingle;

@end

static NSString *const cellIndertifier = @"cellIndertifier";

@implementation LTY_FilmAndSongsViewController
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.dataArray = [NSMutableArray array];
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

#pragma mark -- 返回按钮触发的方法
- (void)leftAction
{
    [self.navigationController popViewControllerAnimated:YES];
    [self.shareButton removeFromSuperview];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tabBarSingle = [TabBarController shareTabBar];
//    NSLog(@"%@",self.DayString);
//    NSLog(@"%@",self.nameString);
//    NSLog(@"%@",self.descString);
    
    // 设置分享按钮
    //分享图标
    UIImage *shareImage = [UIImage imageNamed:@"list_menu_share.png"];
    // 取消渲染
    shareImage = [shareImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.shareButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.shareButton.frame = CGRectMake(SCREENWIDTH - 80, 0, 60, 50);
    [self.shareButton setBackgroundImage:shareImage forState:UIControlStateNormal];
    [self.shareButton addTarget:self action:@selector(shareButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.navigationBar addSubview:self.shareButton];
    
    
    // 添加导航栏退回按钮
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(leftAction)];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    [self.navigationController.navigationBar setBarTintColor:COLOR(22, 88, 240, 1.0)];
    
    self.view.backgroundColor = [UIColor whiteColor];
    // 创建视图
    [self creatDetaletableView];
    
    // 获取数据
    [self getAllDayData];
    
    
    // Do any additional setup after loading the view.
}

// 获取数据
- (void)getAllDayData
{
    NSLog(@"========  %@", self.DayString);
    // 解析数据
    [NetWork networkGETRequestWithURL:self.DayString Paramater:nil ResultBlock:^(id result) {
       // NSLog(@"_+_+_+_+_  %@", result);
        if ([self.JudgeString isEqualToString:@"JudgeString"]) {
            self.songsArr = [NSMutableArray array];
            self.songsArr = [result objectForKey:@"data"];

        }else{
            self.songsArr = [NSMutableArray array];
            self.songsArr = [result objectForKey:@"songs"];
   
        }
        
        // 把model存放刀数组中
        self.dataArray = [LTY_TenSongsModel arrayWithModelByArray:_songsArr];
        self.urlListArray = [NSMutableArray array];
        
        /* 给临时数据库数组初始化*/
        self.sqliteArr = [NSMutableArray array];
        self.sqliteArr = [NSMutableArray arrayWithArray:[FilmAndSongs MR_findAll]];
 //        NSLog(@"____________%ld",self.sqliteArr.count);
        
        for (NSDictionary *dic in _songsArr) {
            // 把url存放到urlListArray中
            if ([[dic objectForKey:@"urlList"] count] > 0) {
            [self.urlListArray addObject:[[[dic objectForKey:@"urlList"] objectAtIndex:0] valueForKey:@"url"]];
                
                /* 对收藏标志进行判断(在重新进入页面时,判断数据库中是否有收藏的值)*/
                
                for (int i  = 0; i < self.dataArray.count; i++) {
                    LTY_TenSongsModel *model = [self.dataArray objectAtIndex:i];
                    model.modelSelect = NO;
                    
                    for (int p = 0; p < self.sqliteArr.count; p++) {
                        
                        if ([[self.sqliteArr[p]valueForKey:@"name"]isEqualToString:[self.dataArray[i]valueForKey:@"name"]]) {
                            
                            model.modelSelect = YES;
                            
                        }
                    }
                }
            }else{
                // 用一个替代变量来替换
                [self.urlListArray addObject:@"http://om32.alicdn.com/443/77443/502542/1770892999_3221858_l.m4a?auth_key=fd586a1cc237bd48e36ec0b6ade0d3c3-1446163200-0-null"];
            }
        }
        
        // 刷新tableview
        if (self.dataArray.count > 0) {
            [self.detailTableview reloadData];
        }
        
        // 数据请求结束的时候使tableview的线显示
        self.detailTableview.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        
    }];
}


// 创建视图
- (void)creatDetaletableView
{
    self.detailTableview = [[UITableView alloc] initWithFrame:CGRectMake(0,0, self.view.frame.size.width, self.view.frame.size.height - 64) style:UITableViewStylePlain];
    self.detailTableview.backgroundColor = [UIColor whiteColor];
    self.detailTableview.delegate = self;
    self.detailTableview.dataSource = self;
    // 创建的时候使tableview的线隐藏
    self.detailTableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.detailTableview registerClass:[LTY_FilmAndSongsTableViewCell class] forCellReuseIdentifier:cellIndertifier];
    
    // 创建表头view
    _headerImage = [[LO_HeaderView alloc] initWithFrame:CGRectMake(0, 0, WIDTHBOUNDS, HEIGHTBOUNDS)];
    _headerImage.headerView.image = [UIImage imageNamed:@"backImage.png"];
    _headerImage.alphaView.image = [LO_GaussianBlur gaussianBlur:1.0f Image:_headerImage.headerView.image];
    _detailTableview.tableHeaderView = _headerImage;
    
    UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 100, 200, 40)];
    //nameLabel.backgroundColor = [UIColor redColor];
    nameLabel.text = self.nameString;
    nameLabel.font = [UIFont systemFontOfSize:22];
    nameLabel.textColor = [UIColor whiteColor];
    [_headerImage addSubview:nameLabel];
    
    UILabel *desLabel = [[UILabel alloc] initWithFrame:CGRectMake(110, 145, 200, 20)];
    //desLabel.backgroundColor = [UIColor cyanColor];
    desLabel.text = self.descString;
    desLabel.font = [UIFont systemFontOfSize:17];
    desLabel.textColor = [UIColor whiteColor];
    [_headerImage addSubview:desLabel];
    
    
    // 把tableview添加到父视图上
    [self.view addSubview:self.detailTableview];
    
    // 导航栏效果
    [self followRollingScrollView:self.detailTableview];
    
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.dataArray.count > 0) {
        return self.dataArray.count;
    
    }else{
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LTY_FilmAndSongsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndertifier];
    
    if (self.dataArray.count > 0) {
        LTY_TenSongsModel *model = [self.dataArray objectAtIndex:indexPath.row];
        // 把model传递给cell
        cell.model = model;
        cell.numberLabel.text = [NSString stringWithFormat:@"%ld", indexPath.row + 1];
        // 把下载的url地址给传递过去
        cell.downLoadString = [self.urlListArray objectAtIndex:indexPath.row];
    }
    
    cell.urlString = self.urlListArray[indexPath.row];
    
    // cell的选中样式 (取消阴影效果)
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 取消点击效果
    //[tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSLog(@"进入播放页面 songId = %@", [self.dataArray[indexPath.row] valueForKey:@"songId"]);
    // 把播放的url地址给传递过去
    NSLog(@"播放的url = %@", [self.urlListArray objectAtIndex:indexPath.row]);
    // 把播放的数组给传递过去
    // self.urlListArray
//    NSString *url = [
    self.tabBarSingle.array = [NSMutableArray array];
    self.tabBarSingle.array = [NSMutableArray arrayWithArray:self.urlListArray];
    
//    self.tabBarSingle.imgName = [self.arr[indexPath.item] pic];
    self.tabBarSingle.index = indexPath.row;
//    self.tabBarSingle.index = 0;
    [self.tabBarSingle.tabBarView.songStopORStart setImage:[UIImage imageNamed:@"pause"] forState:(UIControlStateNormal)];
    
    [self.tabBarSingle play:[self.urlListArray objectAtIndex:indexPath.row]];
    
    // 更新tabBar内容
    self.tabBarSingle.tabBarView.songerName.text = [self.dataArray[indexPath.row] singerName];
    self.tabBarSingle.tabBarView.songName.text = [self.dataArray[indexPath.row] name];
    
    self.tabBarSingle.stopAngle = 1;
    [self.tabBarSingle startAnimation];
    
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}



- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView == _detailTableview) {
        CGFloat dy = scrollView.contentOffset.y;
        NSLog(@"%f", dy);
        if (dy < 0) {
            _headerImage.headerView.frame = CGRectMake(-(-(dy) * WIDTHBOUNDS / HEIGHTBOUNDS) / 2, dy, WIDTHBOUNDS - (dy) * WIDTHBOUNDS / HEIGHTBOUNDS, HEIGHTBOUNDS - dy);
            _headerImage.alphaView.frame = CGRectMake(-(-(dy) * WIDTHBOUNDS / HEIGHTBOUNDS) / 2, dy, WIDTHBOUNDS - (dy) * WIDTHBOUNDS / HEIGHTBOUNDS, HEIGHTBOUNDS - dy);
        }
        _headerImage.alphaView.alpha = (HEIGHTBOUNDS -  CGRectGetHeight(_headerImage.headerView.frame)) / 60 + 1;
    }
}

#pragma mark -- 分享按钮触发的方法
- (void)shareButton:(UIButton *)sender
{
    NSLog(@"分享按钮触发的方法");
    
    NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"backImage" ofType:@"png"];
    
    //构造分享内容
    id<ISSContent> publishContent = [ShareSDK content:@"分享内容"
                                       defaultContent:@"测试一下"
                                                image:[ShareSDK imageWithPath:imagePath]
                                                title:@"ShareSDK"
                                                  url:@"http://www.mob.com"
                                          description:@"这是一条测试信息"
                                            mediaType:SSPublishContentMediaTypeNews];
    
    
    //创建弹出菜单容器
    id<ISSContainer> container = [ShareSDK container];
    [container setIPadContainerWithView:sender arrowDirect:UIPopoverArrowDirectionUp];
    
    //弹出分享菜单
    [ShareSDK showShareActionSheet:container
                         shareList:nil
                           content:publishContent
                     statusBarTips:YES
                       authOptions:nil
                      shareOptions:nil
                            result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
                                
                                if (state == SSResponseStateSuccess)
                                {
                                    NSLog(@"分享成功");
                                }
                                else if (state == SSResponseStateFail)
                                {
                                    NSLog(@"分享失败,错误码:%ld,错误描述:%@", [error errorCode], [error errorDescription]);
                                }
                            }];

    
    
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
